<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../../res/layui/css/layui.css" media="all">
<link rel="stylesheet" href="../../res/css/common/font-awesome.min.css" media="all">
<link rel="stylesheet" href="../../res/layui-config/css/app.css" media="all">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript" src="https://lib.baomitu.com/jquery/1.11.2/jquery.min.js"></script>
<title>零售管理</title>
</script>
</head>
<body>
	<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
		<legend>增加零售订单</legend>
	</fieldset>
	
	<form class="layui-form" action="">
	
	<div class="layui-form-item">
		<label class="layui-form-label">会员名</label>
			<div class="layui-input-block" style="width:200px;">
				<select name="menId" id="memSelect" lay-filter="memSelect">
					<option value=""></option>
				</select>
		    </div>
   </div>
   <input id="anButton" onclick="findAn()" type="button" style="width: 100px;margin-top: -70px;margin-left: 400px;z-index: 999;" lay-submit lay-filter="search"
		class="layui-btn layui-btn-sm kit-btn" value="确认购买"/>
	<div class="layui-form">
		<table class="layui-table" style="width: 880px;" lay-filter="test3" id="add">
			<thead>
				<tr>
					<th lay-data="{field:'id', width:150, sort: true, edit: 'text'}">药品名</th>
					<th lay-data="{field:'amount', width:50, edit: 'text'}">零售数量</th>
					<th lay-data="{field:'price', edit: 'text', width:50}">零售单价</th>
					<th lay-data="{field:'prices', edit: 'text', width:50}">零售总金额</th>
					<th lay-data="{field:'zl', edit: 'text', width:50}">会员折扣率</th>
					<th lay-data="{field:'zj', edit: 'text', width:50}">折扣单价</th>
					<th lay-data="{field:'ze', edit: 'text', width:50}">折扣总金额</th>
					<th lay-data="{fixed: 'right',title: '操作',width: 180,align: 'center',toolbar: '#bardemos'}">操作</th>
				</tr>
			</thead>
		</table>
	</div>
		
	<div class="kit-table">
		<form class="layui-form" lay-filter="kit-search-form">
			<!-- 左上角的两个按钮 -->
			<div class="kit-table-header">
				<div style="width:100px;left: 30px;" class="kit-search-inputs">
					<div class="kit-search-keyword">
						<input type="text" class="layui-input" id="serach-one"
							placeholder="药品.." onKeyUp="lockInput(this,'serach-two')" />
						<button style="left: 170px;" lay-submit lay-filter="search">
							<i class="layui-icon">&#xe615;</i>
						</button>
					</div>
					<div style="width:100px;left: 230px;" class="kit-search-more" id="kit-search-more">
						更多筛选<i class="layui-icon">&#xe61a;</i>
					</div>
				</div>
			</div>
			<!-- 搜索扩展工具条 -->
			<div class="kit-search-mored layui-anim layui-anim-upbit">
				<div class="kit-search-body">
					<div class="layui-form-item">
						<label class="layui-form-label">药品名称</label>
						<div class="layui-input-block">
							<input type="text" name="drugName" id="serach-two"
								placeholder="搜索关键字.." autocomplete="off" class="layui-input"
								onKeyUp="lockInput(this,'serach-one')">
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">药品类型</label>
						<div class="layui-input-block">
							<select name="dtId" id="drug-type">
								<option value=""></option>
							</select>
						</div>
					</div>
					<div class="layui-form-item">
						<div class="layui-inline">
							<label class="layui-form-label">药品价格</label>
							<div class="layui-input-block">
								<div class="layui-input-inline" style="width: 100px;">
									<input type="text" name="priceMin" placeholder="￥"
										autocomplete="off" class="layui-input" maxlength="6"
										onKeyUp="amount(this)">
								</div>
								<div class="layui-form-mid">-</div>
								<div class="layui-input-inline" style="width: 100px;">
									<input type="text" name="priceMax" placeholder="￥"
										autocomplete="off" class="layui-input" maxlength="6"
										onKeyUp="amount(this)">
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="kit-search-footer">
					<button type="reset"
						class="layui-btn layui-btn-sm layui-btn-primary kit-btn reset-btn">重置</button>
					<button lay-submit lay-filter="search"
						class="layui-btn layui-btn-sm kit-btn">确定</button>
				</div>
			</div>
		</form>
		<!-- 操作按钮 -->
		<div class="kit-table-body">
			<table id="demos" lay-filter="demos"></table>
			<script type="text/html" id="bardemos">
		        <a class="layui-btn layui-btn-xs" lay-event="detail">添加到清单</a>
		    </script>
		</div>
	</div>

	<script src="../../res/js/common/jquery-1.11.2.min.js"></script>
	<script>
			//文本框只能输入金额
		    function amount(th){
		        var regStrs = [
		            ['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上，但首位为0
		            ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
		            ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
		            ['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
		        ];
		        for(i=0; i<regStrs.length; i++){
		            var reg = new RegExp(regStrs[i][0]);
		            th.value = th.value.replace(reg, regStrs[i][1]);
		        }
		    }
			//搜索框同步输入
			function lockInput(obj,id){
				$("#"+id).val($(obj).val());
			}
	</script>
	<script src="../../res/layui/layui.all.js"></script>
	<script>
	//查询类型下拉框数据
    var staticData = null;
    $.ajax({ url:"../../member/query.action?page=1&limit=100",
        type:'post',//method请求方式，get或者post
        cache: false,//同步
        dataType:'json',//预期服务器返回的数据类型
        success:function(mes){//res为相应体,function为回调函数
        	//增加及修改类型下拉框内的数据
        	staticData = mes;
        	//循环添加类型搜索框内的数据
        	$.each(mes.data,function(index,item){
        		$("#memSelect").append("<option value="+item.menId+">"+item.menName+"</option>");
        	});
        	//渲染类型搜索框内的下拉框
        	renderForm();
        }
     });
			//显示数据
		    layui.use(['table','upload'], function() {
		    	var admin=getSession();
		    	
		        var table = layui.table,
		            $ = layui.jquery,
		            layer = layui.layer,
		            form = layui.form,
		            laytpl = layui.laytpl;
		        var tableIns = table.render({
		            elem: '#demos',
		            url: '../../drug/showList.action',
		            height: 'full-50', //容器高度
		            page: true,
		            id: 'demos',
		            where:{"comId":comId,"comType":comType},
		            cols: [
		                [{checkbox: true,fixed: true,field:'check'},
		                {field: 'drugName',title: '药名',width: 240},
		                {field: 'dtName',title: '类型',width: 110},
		                {field: 'drugProp',title: '属性',width: 90},
		                {field: 'drugPictrue',title: '图片',width: 90,templet:'<div><img style="height:100%;height:30px;" src="../../{{ d.drugPictrue}}"></div>'},
		                {field: 'drugPrice',title: '价格（元）',width: 166,sort: true},
		                {fixed: 'right',title: '操作',width: 180,align: 'center',toolbar: '#bardemos'}]
		            ],
		            done: function(res, curr, count) {
		            	//隐藏左边全选单选按钮
		            	$("[data-field='check']").css('display','none');
		                $("[data-field = 'drugProp']").children().each(function(){
						    if($(this).text() == '1'){
						    	$(this).text("处方药");
						    } else if ($(this).text() == '0') {
						    	$(this).text("非处方药");
						    }
					  	});
		            },
		            loading: true
		        });
		        
				//查询类型下拉框数据
		        var staticData = null;
		        $.ajax({ url:"../../drugType/showList.action",
                    type:'post',//method请求方式，get或者post
                    cache: false,//同步
                    dataType:'json',//预期服务器返回的数据类型
                    success:function(mes){//res为相应体,function为回调函数
                    	//增加及修改类型下拉框内的数据
                    	staticData = mes;
                    	//循环添加类型搜索框内的数据
                    	$.each(mes.types,function(index,item){
                    		$("#drug-type").append("<option value="+item.dtId+">"+item.dtName+"</option>");
                    	});
                    	//渲染类型搜索框内的下拉框
                    	renderForm();
                    }
                 });
		  
		        table.on('checkbox(demos)', function(obj){
		        	var data = obj.data; //获得当前行数据
		            var layEvent = obj.event; //获得 lay-event 对应的值
		            var tr = obj.tr; //获得当前行 tr 的DOM对象
		            
		            //判断点击药品表第二次不能加
		            if($("#tr"+data.drugId).html()==undefined){
		        	if(obj.checked==true){
		        		//价格
		        		var mony = data.drugPrice;
		        		if($("#memSelect").val()==""){
		        			$("#add").append("<tr class='tabletr' id='tr"+data.drugId+"'><td style='display:none'>"+data.drugId+"</td><td>"+data.drugName+"</td><td><input type='text' id='up_"+data.drugId+"' class='numbers' style='height:20px; border:0px; width:80px;' onKeyUp='num(this)' value='1' /></td><td id='pic_"+data.drugId+"' class='lsd'>"+data.drugPrice+"</td><td id='zong_"+data.drugId+"' class='lsz'></td><td class='zkl' id='zk"+data.drugId+"'>0</td><td class='zka' id='zkMoney_"+data.drugId+"'>0</td><td id='zkzong_"+data.drugId+"' class='zkz'>0</td><td><input type='button' class='layui-btn layui-btn-xs' onclick='changeState(\""+data.drugId+"\")' value='删除'></td></tr>");
		        		}else{
		        		var url="../../member/findById.action";
						  var datas={"menId":$("#memSelect").val()};
						  $.post(url,datas,function(mes){
							  var zk="";
							  if(mes.oper=="非会员"){
								  zk="1";
							  }else if(mes.oper=="普通会员"){
								  zk="0.9";
							  }else if(mes.oper=="高级会员"){
								  zk="0.85";
							  }else if(mes.oper=="顶级会员"){
								  zk="0.8";
							  }
							  $("#add").append("<tr class='tabletr' id='tr"+data.drugId+"'><td style='display:none'>"+data.drugId+"</td><td>"+data.drugName+"</td><td><input type='text' id='up_"+data.drugId+"' class='numbers' style='height:20px; border:0px; width:80px;' onKeyUp='num(this)' value='1' /></td><td id='pic_"+data.drugId+"' class='lsd'>"+data.drugPrice+"</td><td id='zong_"+data.drugId+"' class='lsz'></td><td class='zkl' id='zk"+data.drugId+"'>"+zk+"</td><td name='1' class='zka' id='zkMoney_"+data.drugId+"'  ></td><td id='zkzong_"+data.drugId+"' class='zkz'></td><td><input type='button' class='layui-btn layui-btn-xs' onclick='changeState(\""+data.drugId+"\")' value='删除'></td></tr>");
						  	  $("#zong_"+data.drugId).html((parseFloat($("#up_"+data.drugId).val())*parseFloat(data.drugPrice)).toFixed(2));
						  	  $("#zkMoney_"+data.drugId).html((parseFloat(data.drugPrice)*parseFloat(zk)).toFixed(2));
						  	  $("#zkzong_"+data.drugId).html((parseFloat($("#zong_"+data.drugId).html())*parseFloat(zk)).toFixed(2));
						  },"json");
		        		}
						//数量
			        	var num=$(".numbers").val();
			        	//赋值总价
			        	$("#zong_"+data.drugId+"").text(parseFloat(mony*num).toFixed(2));
			        	if($("#memSelect").val()==""){
							  $(".zkz").html("0");
							  $(".zkl").html("0");
							  $(".zka").html("0");
			        	}
		        	}
		            }
		        });
		        
		        form.on('select(memSelect)', function(data){
		        	if($("#memSelect").val()==""){
						  $(".zkz").html("0");
						  $(".zkl").html("0");
						  $(".zka").html("0");
		        	}else{
		        		var url="../../member/findById.action";
						  var data={"menId":$("#memSelect").val()};
						  $.post(url,data,function(mes){
							  
							  var zk="";
							  if(mes.oper=="非会员"){
								  zk="1";
							  }else if(mes.oper=="普通会员"){
								  zk="0.9";
							  }else if(mes.oper=="高级会员"){
								  zk="0.85";
							  }else if(mes.oper=="顶级会员"){
								  zk="0.8";
							  }
							  $.each($(".zkl"),function(index,item){
								  $("#"+item.id).html(zk);
								  $("#"+item.id).next().html((parseFloat($("#"+item.id).prev().prev().html())*parseFloat(zk)).toFixed(2));
								  $("#"+item.id).next().next().html((parseFloat($("#"+item.id).prev().html())*parseFloat(zk)).toFixed(2));
							  });
							  
						  },"json");
		        	}
				  
				})
		      	//点击药品表格加入零售--添加到清单按钮
		        $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
		        	
		        	var index = $(this).attr('data-index'); var tableBox = $(this).parents('.layui-table-box');
		        	//存在固定列
			    if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) { 
			    	tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l"); }
			    else { tableDiv = tableBox.find(".layui-table-body.layui-table-main"); }
		        	var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I"); if (checkCell.length>0) { checkCell.click(); } }); 
		        $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) { e.stopPropagation(); });
		        
		        //监听搜索表单提交
		        form.on('submit(search)', function(data) {  
		            //带条件查询
		            tableIns.reload({
		                where: data.field,
		                page: { curr: 1 }
		            });
		            $('.kit-search-mored').hide();
		            return false;
		        });
		        //渲染 修改和增加弹出层
			    function showlayer(d){
			    	laytpl($('#edit-tpl').html()).render(d,function(html) {
	                    layer.open({
	                        type: 1,
	                        title: '表单',
	                        content: html,
	                        area: ['800px', '430px'],
	                        btn: ['提交', '重置', '取消'],
	                        yes: function(index, layero) {
	                            editIndex = index;
	                            $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
	                        },
	                        btn2: function(index, layero) {
	                            $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
	                            return false;
	                        },
	                        success: function() {
	                            form.render(null, 'form-edit');
	                        }
	                    });
	                    upload();
	                });
			    }
		        //监听工具条按钮点击
		        table.on('tool(demos)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
		            var data = obj.data; //获得当前行数据
		            var layEvent = obj.event; //获得 lay-event 对应的值
		            var tr = obj.tr; //获得当前行 tr 的DOM对象
		
		            if (layEvent === 'detail') { //查看
		            	alert(1);
		            }
		        });
		        //表单渲染
		        form.render(null, 'kit-search-form');
		        //更多筛选点击事件
		        $('#kit-search-more').on('click', function() {
		            $('.kit-search-mored').toggle();
		        });
		    });
		  	//重新渲染表单
		  	function renderForm(){ 
	  			layui.use('form', function(){ 
		  			var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加() 
		  			form.render(); 
	  			}); 
	  		}
		    //ajax加载动画
		    $(function () {
		    	
		    	
		    	
	            $.ajaxSetup({
	                layerIndex:-1,
	                beforeSend: function () {
	                    this.layerIndex = layer.load(1, { shade: [0.8, '#ffffff']});
	                },
	                complete: function () {
	                    layer.close(this.layerIndex);
	                },
	                error: function () {
	                    layer.alert('部分数据加载失败，可能会导致页面显示异常，请刷新后重试', {
	                        skin: 'layui-layer-molv'
	                       , closeBtn: 0
	                       , shift: 4 //动画类型
	                    });
	                }
	            });
	        });
		    function num(obj){
		    	if(isNaN($("#"+obj.id).val())){
		    		$("#"+obj.id).val(1);
		    	}
				
		    	var url="../../drugInv/findDrugId.action";
		    	var data={"drugId":$("#"+obj.id).parent().prev().prev().html()};
		    	$.post(url,data,function(mes){
		    		$.each(mes,function(index,item){
		    			if($("#"+obj.id).val()>item.diAmount){
		    				layer.msg("零售库存不足");
		    				$("#"+obj.id).val(item.diAmount);
		    			}else{
		    				$("#"+obj.id).parent().next().next().html(parseFloat($("#"+obj.id).parent().next().html())*parseFloat($("#"+obj.id).val()));		 
		    				$("#"+obj.id).parent().next().next().next().next().next().html(parseFloat($("#"+obj.id).parent().next().next().next().next().html())*parseFloat($("#"+obj.id).val()));
		    		    	
		    			}
		    		});
		    	},"json");
		    	
		    }
		    function changeState(id){
		    	$("#tr"+id).remove();
		    }
		    function findAn(){
		    	var sum="";
		    	$.each($(".tabletr"),function(index,item){
		    		sum+=$(item).children().html()+","+$(item).children().next().next().children().val()+"@";
		    	});
				
		    	var url="../../branchSale/addSale.action";
		    	var datas={"sum":sum,"menId":$("#memSelect").val()};
		    	$.post(url,datas,function(mes){
		    		if(mes.status==1){
		    			parent.layer.msg(mes.msg);
		    			var index=parent.layer.getFrameIndex(window.name);
		    			parent.layer.close(index);
		    		}else{
		    			parent.layer.msg("保存失败");
		    		}
		    	},"json");
		    	
		    }
		    var comId="";
		    var comType="";
		    $(function(){
		    	getSession();
		    })
		     
		    function getSession(){
				var admin = null;
				$.ajax({ 
		        	url:"../../admin/getSession.action",
	                type:'post',
	                async:false,
	                dataType:'json',
	                success:function(mes){
	                	if (mes!=null && mes!="") {
	                		comId = mes.comId;
	                		comType=mes.comType;
						} else {
							location.href = "../admin/login.html";
						}
	                },
	                error: function(){
	                	location.href = "../admin/login.html";
	                }
	        	});
				return admin;
			}
		</script>
</body>
</html>